package com.ruoyi.web.controller.net;

import com.ruoyi.net.domain.*;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.*;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 网元-QOS配置-流策略Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-QOS配置-流策略")
@RestController
@RequestMapping("/element/qos/strategy")
public class ElementQosStrategyController extends BaseController {
    @Autowired
    private IElementQosStrategyService elementQosStrategyService;

    @Autowired
    private IElementQosFlowService qosFlowService;

    @Autowired
    private IElementQosActionService qosActionService;

    @Autowired
    private IElementQosActionSuperviseService qosActionSuperviseService;
    @Autowired
    private IElementQosActionShapeService qosActionShapeService;
    @Autowired
    private IElementQosActionRedirectService qosActionRedirectService;
    @Autowired
    private IElementQosActionPhbService qosActionPhbService;
    @Autowired
    private IElementQosActionMappingService qosActionMappingService;
    @Autowired
    private IElementQosActionImageService qosActionImageService;
    @Autowired
    private IElementQosActionDispatchService qosActionDispatchService;
    @Autowired
    private IElementQosActionCrowdService qosActionCrowdService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 查询网元-QOS配置-流策略列表
     */
    @ApiOperation(value = "查询网元-QOS配置-流策略列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:strategy:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementQosStrategy elementQosStrategy) {
        startPage();
        List<ElementQosStrategy> list = elementQosStrategyService.selectElementQosStrategyList(elementQosStrategy);
        return getDataTable(list);
    }

    /**
     * 导出网元-QOS配置-流策略列表
     */
    @ApiOperation(value = "导出网元-QOS配置-流策略列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:strategy:export')")
    @Log(title = "网元-QOS配置-流策略", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementQosStrategy elementQosStrategy) {
        List<ElementQosStrategy> list = elementQosStrategyService.selectElementQosStrategyList(elementQosStrategy);
        ExcelUtil<ElementQosStrategy> util = new ExcelUtil<ElementQosStrategy>(ElementQosStrategy.class);
        util.exportExcel(response, list, "网元-QOS配置-流策略数据");
    }

    /**
     * 获取网元-QOS配置-流策略详细信息
     */
    @ApiOperation(value = "获取网元-QOS配置-流策略详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:strategy:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementQosStrategyService.selectElementQosStrategyById(id));
    }

    /**
     * 新增网元-QOS配置-流策略
     */
    @ApiOperation(value = "新增网元-QOS配置-流策略", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:strategy:add')")
    @Log(title = "网元-QOS配置-流策略", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementQosStrategy elementQosStrategy) {
        ElementQosStrategyAction qosStrategyAction = elementQosStrategy.getQosStrategyAction();
        if (qosStrategyAction != null) {
            elementQosStrategy.setActionRelation(qosStrategyAction.getClassifyName() + "|" + qosStrategyAction.getActionName());
        }
        return toAjax(elementQosStrategyService.insertElementQosStrategy(elementQosStrategy));
    }

    /**
     * 修改网元-QOS配置-流策略
     */
    @ApiOperation(value = "修改网元-QOS配置-流策略", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:strategy:edit')")
    @Log(title = "网元-QOS配置-流策略", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementQosStrategy elementQosStrategy) {
        ElementQosStrategyAction qosStrategyAction = elementQosStrategy.getQosStrategyAction();
        if (qosStrategyAction != null) {
            elementQosStrategy.setActionRelation(qosStrategyAction.getClassifyName() + "|" + qosStrategyAction.getActionName());
        }
        return toAjax(elementQosStrategyService.updateElementQosStrategy(elementQosStrategy));
    }

    /**
     * 删除网元-QOS配置-流策略
     */
    @ApiOperation(value = "删除网元-QOS配置-流策略", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:strategy:remove')")
    @Log(title = "网元-QOS配置-流策略", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementQosStrategyService.deleteElementQosStrategyByIds(ids));
    }
    /**
     * 激活设备
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementQosStrategy entity = elementQosStrategyService.selectElementQosStrategyById(id);
        entity.setStatus("1");
        if (sendXml(entity)){
            return toAjax(elementQosStrategyService.updateElementQosStrategy(entity));
        }else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementQosStrategy entity = elementQosStrategyService.selectElementQosStrategyById(id);
        entity.setStatus("0");
        if (sendXml(entity)){
            return toAjax(elementQosStrategyService.updateElementQosStrategy(entity));
        }else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /*<qos-cfgs xmlns="http://fiberhome.com/fhnw/yang/qos/fos-qos">
    <qos-tpl>
      <traffic-policy-cfgs>
        <traffic-policy-cfg>
          <policy-name>fef4</policy-name>
          <cb-cfg>
            <class-name>gr4</class-name>
            <traffic-behavior>
              <action>pass</action>
              <car-cfg>
                <cir>3</cir>
                <pir>5</pir>
                <cbs>16384</cbs>
                <pbs>32768</pbs>
                <car-mode>rfc-mef</car-mode>
                <color-aware>blind</color-aware>
              </car-cfg>
              <mirror-cfg>
                <mirror-to-type>interface</mirror-to-type>
              </mirror-cfg>
              <behavior-name>gg55</behavior-name>
            </traffic-behavior>
            <queue-behavior-cfgs>
              <queue-behavior-cfg>
                <queue-id>be</queue-id>
                <queue-behavior>
                  <congestion-cfg>
                    <congestion-mode>wred</congestion-mode>
                    <wred-name/>
                  </congestion-cfg>
                  <size>0</size>
                </queue-behavior>
              </queue-behavior-cfg>
              <queue-behavior-cfg>
                <queue-id>af1</queue-id>
                <queue-behavior>
                  <scheduling-cfg>
                    <sch-mode>wfq</sch-mode>
                    <wfq-value>1</wfq-value>
                  </scheduling-cfg>
                  <shaping-cfg>
                    <cir>2</cir>
                    <pir>5</pir>
                    <cbs>16384</cbs>
                    <pbs>32768</pbs>
                  </shaping-cfg>
                  <size>0</size>
                </queue-behavior>
              </queue-behavior-cfg>
            </queue-behavior-cfgs>
          </cb-cfg>
        </traffic-policy-cfg>
      </traffic-policy-cfgs>
    </qos-tpl>
  </qos-cfgs>*/

    private boolean sendXml(ElementQosStrategy entity) {
        boolean isSend = true;
        // TODO: 2024/11/28  设备联调，添加并激活
       /* if (sysConfigService.selectDebugEnabled()) {
            NetElement netElement = netElementService.getCacheObject(entity.getElementId());
            deviceManager.getDevice(netElement.getIp());
            String operation = "create";
            if ("0".equals(entity.getStatus())) {
                operation = "remove";
            }

            ElementQosStrategyAction qosStrategyAction = entity.getQosStrategyAction();
            ElementQosFlow qosFlow = qosFlowService.selectElementQosFlowById(entity.getFlowId());
            ElementQosAction qosAction = qosActionService.selectElementQosActionById(entity.getActionId());

            // 流量监管
            ElementQosActionSupervise qosActionSupervise = qosActionSuperviseService.selectElementQosActionSuperviseById(qosAction.getId());
            // 流量整形
            ElementQosActionShape qosActionShape = qosActionShapeService.selectElementQosActionShapeById(qosAction.getId());
            // 重定向配置
            ElementQosActionRedirect qosActionRedirect = qosActionRedirectService.selectElementQosActionRedirectById(qosAction.getId());
            // 指配PHB配置
            ElementQosActionPhb qosActionPhb = qosActionPhbService.selectElementQosActionPhbById(qosAction.getId());
            // 重映射配置
            ElementQosActionMapping qosActionMapping = qosActionMappingService.selectElementQosActionMappingById(qosAction.getId());
            // 镜像配置
            ElementQosActionImage qosActionImage = qosActionImageService.selectElementQosActionImageById(qosAction.getId());
            // 调度策略
            ElementQosActionDispatch qosActionDispatch = qosActionDispatchService.selectElementQosActionDispatchById(qosAction.getId());
            // 拥塞策略
            ElementQosActionCrowd qosActionCrowd = qosActionCrowdService.selectElementQosActionCrowdById(qosAction.getId());

            StringBuilder xml = new StringBuilder();
            xml.append("<qos-cfgs xmlns=\"http://fiberhome.com/fhnw/yang/qos/fos-qos\">" +
                    "    <qos-tpl>" +
                    "      <traffic-policy-cfgs>" +
                    "        <traffic-policy-cfg>" +
                    "          <policy-name>" + entity.getStrategyName() + "</policy-name>" +
                    "          <cb-cfg>" +
                    "            <class-name>" + qosFlow.getClassifyName() + "</class-name>" +
                    "            <traffic-behavior>" +
//                    "              <action>pass</action>" +
                    "              <action>" + qosAction.getAction() + "</action>");
            if (("pass".equalsIgnoreCase(qosAction.getAction()) || "0".equals(qosAction.getAction()))
            && qosActionSupervise != null) {
                // -------start 流量监管
                xml.append("              <car-cfg>" +
                        "                <cir>" + qosActionSupervise.getCir() + "</cir>" +
                        "                <pir>" + qosActionSupervise.getPir() + "</pir>" +
                        "                <cbs>" + qosActionSupervise.getCbs() + "</cbs>" +
                        "                <pbs>" + qosActionSupervise.getPbs() + "</pbs>" +
                        "                <car-mode>" + qosActionSupervise.getFlowMode() + "</car-mode>" +
                        "                <color-aware>" + qosActionSupervise.getCmColor() + "</color-aware>" +
                        "              </car-cfg>");
                // -------end 流量监管
            }
            if (qosActionImage != null
                    && ("enable".equalsIgnoreCase(qosActionImage.getImageEnable()) || "1".equals(qosActionImage.getImageEnable()))) {
                // -------start 镜像
            xml.append("              <mirror-cfg>" +
                        "                <mirror-to-type>" + qosActionImage.getImageToType() + "</mirror-to-type>" +
                        "                <mirror-if-name>" + qosActionImage.getPortName() + "</mirror-if-name>" +
                        "              </mirror-cfg>");
                // -------end 镜像
            }
            if (qosActionShape != null) {
                // -----start 流量整形
                xml.append("                  <shaping-cfg>" +
                        "                    <cir>" + qosActionShape.getCir() + "</cir>" +
                        "                    <pir>" + qosActionShape.getPir() + "</pir>" +
                        "                    <cbs>" + qosActionShape.getCbs() + "</cbs>" +
                        "                    <pbs>" + qosActionShape.getPbs() + "</pbs>" +
                        "                  </shaping-cfg>");
                // -----end 流量整形
            }
            if (qosActionDispatch != null) {
                // -----start 调度策略
            xml.append("                  <scheduling-cfg>" +
                        "                    <sch-mode>" + qosActionDispatch.getDispatchStrategy() + "</sch-mode>" +
                        "                    <wfq-value>" + qosActionDispatch.getDispatchStrategyWeight() + "</wfq-value>" +
                        "                  </scheduling-cfg>");
                // -----end 调度策略
            }
            //  ---start 重定向配置
            if (("pass".equalsIgnoreCase(qosAction.getAction()) || "0".equals(qosAction.getAction())) && qosActionRedirect != null) {
            xml.append("                  <redir-cfg>" +
                        "                    <redir-type>" + qosActionRedirect.getRedirectType() + "</redir-type>" +
                        "                    <redir-vrf-name>" + qosActionRedirect.getVrfName() + "</redir-vrf-name>" +
                        "                    <redir-if-name>" + qosActionRedirect.getPortName() + "</redir-if-name>" +
                        "                    <redir-next-ipv4>" + qosActionRedirect.getIp() + "</redir-next-ipv4>" +
                        "                  </redir-cfg>");
                //  ---end 重定向配置
            }
            if (("pass".equalsIgnoreCase(qosAction.getAction()) || "0".equals(qosAction.getAction()))
                    && qosActionMapping != null
                    && ("1".equals(qosActionMapping.getMappingEnable()) || "enable".equalsIgnoreCase(qosActionMapping.getMappingEnable()))) {
                // ---start 重映射
            xml.append("                  <remark-cfg>" +
                        "                    <remark-type>" + qosActionMapping.getMappingType() + "</remark-type>" +
                        "                    <remark-priority>" + qosActionMapping.getMappingLevel() + "</remark-priority>" +
                        "                  </remark-cfg>");
                // ---end 重映射
            }

            if (("pass".equalsIgnoreCase(qosAction.getAction()) || "0".equals(qosAction.getAction()))
                    && qosActionPhb != null
                    && ("1".equals(qosActionPhb.getAssignPhbEnable()) || "enable".equalsIgnoreCase(qosActionPhb.getAssignPhbEnable()))) {
                // ----start 指定PHB mark-phb-cfg phb-value mark-color
            xml.append("                  <mark-phb-cfg>" +
                        "                    <phb-value>" + qosActionPhb.getAssignServiceLevel() + "</phb-value>" +
                        "                    <mark-color>" + qosActionPhb.getAssignColor() + "</mark-color>" +
                        "                  </mark-phb-cfg>");
                // ----end 指定PHB
            }


            if (("pass".equalsIgnoreCase(qosAction.getAction()) || "0".equals(qosAction.getAction()))
                    && qosActionCrowd != null) {
                // strart 拥塞策略 congestion-cfg
                xml.append("                  <congestion-cfg>" +
                        "                    <congestion-mode>" + qosActionCrowd.getServiceLevel() + "</congestion-mode>" +
                        "                    <wred-name>" + qosActionCrowd.getCrowdStrategy() + "</wred-name>" +
                        "                  </congestion-cfg>");
                // ----end 拥塞策略
            }
                    xml.append("<behavior-name>" + qosAction.getActionName() + "</behavior-name>" +
                    "            </traffic-behavior>" +
                    // -------start 队列行为
                    "            <queue-behavior-cfgs>" +
                    "              <queue-behavior-cfg>" +
                    "                <queue-id>be</queue-id>" +
                    "                <queue-behavior>" +
                    "                  <congestion-cfg>" +
                    "                    <congestion-mode>wred</congestion-mode>" +
                    "                    <wred-name/>" +
                    "                  </congestion-cfg>" +
                    "                  <size>0</size>" +
                    "                </queue-behavior>" +
                    "              </queue-behavior-cfg>" +
                    "              <queue-behavior-cfg>" +
                    "                <queue-id>af1</queue-id>" +
                    "                <queue-behavior>" +
                    "                  <size>0</size>" +
                    "                </queue-behavior>" +
                    "              </queue-behavior-cfg>" +
                    "            </queue-behavior-cfgs>" +

                    // -------start 队列行为
                    "          </cb-cfg>" +
                    "        </traffic-policy-cfg>" +
                    "      </traffic-policy-cfgs>" +
                    "    </qos-tpl>" +
                    "  </qos-cfgs>");
            System.out.println(xml.toString());
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }*/
        return isSend;
    }
}